package com.yanchangapp.ui.activity._n_manage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanchangapp.R;
import com.yanchangapp.adapter._n_manage.WorkItemListAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.WorkItemBean;
import com.yanchangapp.model.request.MakeDailyPlanRequest;
import com.yanchangapp.ui.presenter.WorkItemAtPresenter;
import com.yanchangapp.ui.view.WorkItemAtView;
import com.yanchangapp.widget.SetDieTimeDialog;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.YCLoadingView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
 * page: 我的工作项  ==> 操作 设置天数/勾选生成计划 点击条目->查看详情...
 *
 * 注意工作项adapter只应当适用于工作项活动...
 *
 * 获取列表都是ok的....
 */
public class WorkItemActivity extends BaseActivity<WorkItemAtView, WorkItemAtPresenter> implements WorkItemAtView {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.tv_publish_now)
    TextView tvPublishNow;
    @BindView(R.id.btnMakePlan)
    Button btnMakePlan;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.rvPlanItem)
    RecyclerView rvPlanItem;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tvDes)
    TextView tvDes;
    @BindView(R.id.llEmptyMsg)
    LinearLayout llEmptyMsg;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;

    // 是否是编辑状态
    private boolean isEditType = false;
    private WorkItemListAdapter mWorkItemListAdapter;
    private List<WorkItemBean> mWorkItemBeans = new ArrayList<>();
    // 当前页数....
    private int curPage = 1;

    public static void show(Activity activity){
        Intent intent = new Intent(activity,WorkItemActivity.class);
        activity.startActivity(intent);
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE){
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }
                break;
            case EMPTY:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.GONE){
                    llEmptyMsg.setVisibility(View.VISIBLE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.GONE){
                    refreshLayout.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }

                tvPublishNow.setVisibility(View.VISIBLE);
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }

                // 设置布局隐藏
                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }
                break;
        }
    }


    private void clearAndChangeRv(){
        for (int i=0;i<mWorkItemBeans.size();i++){
            mWorkItemBeans.get(i).isSelected = false;
        }
        mWorkItemListAdapter.setEditType(isEditType);
        mWorkItemListAdapter.notifyDataSetChanged();
    }

    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_work_item;
    }

    @Override
    protected WorkItemAtPresenter createPresenter() {
        return new WorkItemAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("我的工作项");
        tvPublishNow.setText("");
        tvDes.setText("暂无工作项");
        initAdapter();
    }

    private void initAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rvPlanItem.setLayoutManager(manager);
        mWorkItemListAdapter = new WorkItemListAdapter(mWorkItemBeans);
        mWorkItemListAdapter.setEditType(true);
        rvPlanItem.setAdapter(mWorkItemListAdapter);
    }


    @Override
    protected void initData() {
        curPage = 1;
        setLoadingState(LoadingType.LOADING);
        mPresenter.queryWorkItemLists(curPage);
    }

    @Override
    protected void initListener() {
        // 返回事件
        ivToolbarNavigation.setOnClickListener(v -> finish());

        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                curPage = 1;
                mPresenter.queryWorkItemLists(curPage);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                curPage ++;
                mPresenter.queryWorkItemLists(curPage);
            }
        });

        btnMakePlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 校验是否选择
                checkWhichSelected();
            }
        });


        mWorkItemListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.checkbox){
                    // 进行该item的设置
                    mWorkItemBeans.get(position).isSelected = !mWorkItemBeans.get(position).isSelected;
                }else if (view.getId() == R.id.llTime){
                    // 设置期限的点击事件...
                    Integer time =  mWorkItemBeans.get(position).getTime();
                    showSetDieTimeDialog(position,time);
                }
            }
        });

        // 点击事件分别处理....
        mWorkItemListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (isEditType){
                    mWorkItemBeans.get(position).isSelected = !mWorkItemBeans.get(position).isSelected;
                    mWorkItemListAdapter.notifyItemChanged(position);
                }else {
                    WorkItemDetailActivity.show(WorkItemActivity.this,mWorkItemBeans.get(position).getId());
                }
            }
        });
    }

    /**
     * 展示设置时间期限的弹窗...
     */
    private void showSetDieTimeDialog(int position,Integer time){
        new SetDieTimeDialog.Builder(this)
                .setPrice(time)
                .setEnsureListener(dieTime -> {
                    mWorkItemBeans.get(position).setTime(dieTime);
                    mWorkItemListAdapter.notifyItemChanged(position);
                }).build().show();
    }

    private void checkWhichSelected(){
        List<MakeDailyPlanRequest> mList = new ArrayList<>();
        for (int i=0;i<mWorkItemBeans.size();i++){
            WorkItemBean workItemBean = mWorkItemBeans.get(i);
            if (workItemBean.isSelected){
                // 设置ID以及时间...
                mList.add(new MakeDailyPlanRequest(workItemBean.getId(),
                        workItemBean.getTime() == null ? 1:workItemBean.getTime()));
            }
        }
        if (mList.size() == 0){
            UIUtils.showToast("请选择工作项");
        }else {
            mPresenter.makeDailyPlan(mList);
        }
    }

    private void showBottom(){
        if (mWorkItemBeans.size() == 0){
            if (bottom.getVisibility() == View.VISIBLE){
                bottom.setVisibility(View.GONE);
            }
            setLoadingState(LoadingType.EMPTY);
        }else {
            if (bottom.getVisibility() == View.GONE){
                bottom.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void queryWorksSuccess(List<WorkItemBean> list) {
        setLoadingState(LoadingType.SUCCESS);
        if (curPage == 1){
            refreshLayout.finishRefresh();
            // 清楚列表,填充数据,进行刷新操作
            mWorkItemBeans.clear();
            mWorkItemBeans.addAll(list);
            mWorkItemListAdapter.notifyDataSetChanged();
        }else {
            // 说明刷到有数据....
            if (list != null && list.size() != 0){
                // 添加并进行刷新操作....
                refreshLayout.finishLoadMore();
                mWorkItemBeans.addAll(list);
                mWorkItemListAdapter.notifyDataSetChanged();
            }else {
                refreshLayout.finishLoadMoreWithNoMoreData();
                curPage --;
            }
        }
        showBottom();
    }

    @Override
    public void queryWorksFailure(String err) {
        UIUtils.showToast(err);
        if (curPage == 1){
            refreshLayout.finishRefresh();
            if (mWorkItemBeans.size() == 0){
                setLoadingState(LoadingType.ERROR);
            }
        }else {
            curPage --;
            refreshLayout.finishLoadMore();
        }
        showBottom();
    }

    @Override
    public void makePlanSuccess(String success) {
        UIUtils.showToast(success);
        // 自动刷新
        initData();
    }

    @Override
    public void makePlanFailure(String err) {
        UIUtils.showToast(err);
    }
}
